package server.lunch;

import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.apache.shardingsphere.transaction.core.TransactionTypeHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import server.dao.OrderDao;
import server.enitity.Order;
import server.service.OrderService;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @ClassName AppLunch
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2021/12/21 上午12:33
 * @Version V1.0
 * @Since JDK 11
 */
@Component
public class AppLunch implements ApplicationRunner {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderService orderService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        orderService.transaction(buildOrderList(2));
    }



    public static List<Order> buildOrderList(int num) {
        List<Order> list = new ArrayList<>(num);
        Random random = new Random();
        Date date = new Date();
        SnowflakeShardingKeyGenerator snowflakeShardingKeyGenerator = new SnowflakeShardingKeyGenerator();
        for (int i = 0; i < num; i++) {
            Order order = new Order();
            //id可以通过雪花算法生成
            long l = Long.parseLong("" + snowflakeShardingKeyGenerator.generateKey());
            order.setId(l);
            order.setUserId(random.nextInt(1000000) + 1);
            order.setItemId(random.nextInt(10000) + 1);
            order.setCount(random.nextInt(10) + 1);
            BigDecimal bigDecimal = new BigDecimal(order.getItemId() * 10);
            order.setPrice(bigDecimal);
            order.setPriceSum(bigDecimal.multiply(BigDecimal.valueOf(order.getCount())));
            order.setCreateTime(date);
            order.setUpdateTime(date);
            order.setOrderNo("WX_" + date.getTime() + "_" + order.getId());
            order.setBussinessId("123456");
            order.setStatus((short) 1);
            order.setItemName("A");
            list.add(order);
        }
        return list;
    }

    public static Comparable<?>  getId(Long workerId) {
        if (!(workerId >= 0 && workerId < 1024L)) {
            throw new RuntimeException("workerId is not support range must be [0,1024)");
        }
        SnowflakeShardingKeyGenerator snowflakeShardingKeyGenerator = new SnowflakeShardingKeyGenerator();
        snowflakeShardingKeyGenerator.getProperties().put("worker.id", String.valueOf(workerId));
        Comparable<?> generateKey = snowflakeShardingKeyGenerator.generateKey();
        return generateKey;
    }
}
